package ch02sl.jd.jd1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.util.Iterator;

public class XMLParseDel {

    public  void showPhoneInfo() {
        Document doc = null;
        try {
            SAXReader saxReader = new SAXReader();
            doc =  saxReader.read(new File("src/test/java/ch02sl/jd/Student.XML"));
        }
         catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        Element root =  doc.getRootElement();

        for (Iterator<Element> it = root.elementIterator("student"); it.hasNext(); ) {
            Element brand = it.next();
            if ("3".equals(brand.attributeValue("id"))) {
                root.remove(brand);
            }
        }
        // 获取所有student节点
        Iterator<Element> iter = root.elementIterator();

        while (iter.hasNext()) {
            Element element = iter.next();
            // 获取每个student节点的name节点
            Element nameElement = element.element("name");
            // 获取每个student节点的course节点
            Element courseElement = element.element("course");
            // 获取每个student节点的score节点
            Element scoreElement = element.element("score");
            // 输出每个student节点的name节点和score节点
            System.out.println("name:" + nameElement.getText() + ",score:" + scoreElement.getText());
            // 输出每个student节点的course节点
            System.out.println("course:" + courseElement.getText());

        }

        // 保存修改后的XML文件
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        try {
            XMLWriter writer = new XMLWriter(new FileWriter("src/test/java/ch02sl/jd/Student.XML"), format);
            writer.write(doc);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        XMLParseDel parse = new XMLParseDel();
        parse.showPhoneInfo();
    }
}
